package com.module.comm.utils;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.maven.shared.invoker.DefaultInvocationRequest;
import org.apache.maven.shared.invoker.DefaultInvoker;
import org.apache.maven.shared.invoker.InvocationOutputHandler;
import org.apache.maven.shared.invoker.InvocationRequest;
import org.apache.maven.shared.invoker.Invoker;
import org.apache.maven.shared.invoker.InvokerLogger;
import org.apache.maven.shared.invoker.MavenInvocationException;
import org.apache.maven.shared.invoker.PrintStreamLogger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.system.handle.model.ResponseFrame;

/**
 * Maven操作类
 * @author yuejing
 * @date 2019年3月24日 下午8:08:41
 * @version V1.0.0
 */
public class MavenUtil {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(MavenUtil.class);

	/**
	 * 执行Maven的命令
	 * @param pomPath
	 * @param mavenHomePath
	 * @param commands
	 * @return
	 */
	public static ResponseFrame execute(String pomPath, String mavenHomePath, List<String> commands) {
		ResponseFrame frame = new ResponseFrame();
		InvocationRequest request = new DefaultInvocationRequest();
		request.setPomFile(new File(pomPath));
		request.setGoals(commands);// Collections.singletonList("clean", "install") );
		//request.setGoals( Collections.singletonList("compile") );

		Invoker invoker = new DefaultInvoker();
		invoker.setMavenHome(new File(mavenHomePath));
		invoker.setLogger(new PrintStreamLogger(System.err,  InvokerLogger.ERROR) {
		} );
		StringBuffer outputSb = new StringBuffer();
		invoker.setOutputHandler(new InvocationOutputHandler() {
			@Override
			public void consumeLine(String s) throws IOException {
				LOGGER.info(s);
				outputSb.append(s);
			}
		});
		/*try {
			invoker.execute( request );
		}
		catch (MavenInvocationException e) {
			LOGGER.error(e.getMessage(), e);
		}*/

		try{
			if(invoker.execute( request ).getExitCode() == 0) {
				frame.setSucc();
			}else{
				frame.setCode(-20);
			}
		}catch (MavenInvocationException e) {
			LOGGER.error(e.getMessage(), e);
			frame.setCode(-20);
		}
		frame.setMessage(outputSb.toString());
		return frame;
	}
}
